package com.xianyun.site.iblog.user.executor.handle.impl;

import com.alibaba.cola.dto.Response;
import com.xianyun.common.core.utils.FormatUtils;
import com.xianyun.site.iblog.convertor.SystemUserConvertor;
import com.xianyun.site.support.api.dubbo.SupportEchoService;
import com.xianyun.site.iblog.common.core.exception.LoginCheckErrorException;
import com.xianyun.site.iblog.common.core.exception.UserNotRegisterException;
import com.xianyun.site.support.dto.SmsCheckQry;
import com.xianyun.site.iblog.dto.user.SystemUserLoginQry;
import com.xianyun.site.iblog.dto.user.data.SystemUserDTO;
import com.xianyun.site.iblog.gatewayimpl.database.SystemUserMapper;
import com.xianyun.site.iblog.gatewayimpl.database.domainobject.SystemUserDO;
import com.xianyun.site.iblog.user.executor.handle.BaseLoginCheckHandle;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 手机验证码登录
 * @author mac_zyj
 */
@Slf4j
@Component
public class IMobileCodeCheckHandle extends BaseLoginCheckHandle {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Reference
    private SupportEchoService supportEchoService;

    /**
     * TODO 定义对应的登录错误异常
     * @param qry 登录查询
     * @return 结果
     */
    @Override
    public SystemUserDTO loginExecute(SystemUserLoginQry qry) {
        Assert.isTrue(FormatUtils.isNumLegal(qry.getExtendKey()),"手机号格式错误请确认手机格式");
        Response smsCheckResponse = supportEchoService.checkSmsCode(initSmsCheckQry(qry));
        if(smsCheckResponse.isSuccess()){
            SystemUserDO searchData= systemUserMapper.getSystemUserByMobile(qry.getExtendKey());
            if (null!=searchData){
                return SystemUserConvertor.toSystemUserDTO(searchData);
            } else {
                log.debug("Mobile:{},-- 请确认手机是否注册",qry.getExtendKey());
                throw new UserNotRegisterException("BIZ_CLOUD_BLOG_LOGIN");
            }
        }else {
            log.debug("Mobile:{},-- 手机号或验证码有误",qry.getExtendKey());
            throw new LoginCheckErrorException("BIZ_CLOUD_BLOG_LOGIN");
        }
    }

    private SmsCheckQry initSmsCheckQry(SystemUserLoginQry qry){
        SmsCheckQry smsCheckQry = new SmsCheckQry();
        smsCheckQry.setActionEvent("云博客-用户模块-登录操作");
        smsCheckQry.setType(1);
        smsCheckQry.setModel("登录");
        smsCheckQry.setPhoneNumber(qry.getExtendKey());
        smsCheckQry.setCode(qry.getCredentials());
        smsCheckQry.setSessionId(qry.getSessionId());
        return smsCheckQry;
    }
}
